package handler

import (
	"car-order-sys/cache"
	"car-order-sys/models"
	"encoding/json"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Detail(c *gin.Context) {
	id := c.Query("id")
	var order models.CarOrderList
	redis_key := "detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("car_orders").Select(
			"cars.id AS OrderId",
			"cars.car_model AS CarName",
			"cars.car_name AS CarPrice",
			"cars.car_price AS CarModel",
			"car_orders.order_code AS OrderCode",
			"car_orders.order_num AS OrderNum",
			"car_orders.order_price AS OrderPrice",
		).Joins("LEFT JOIN cars ON cars.id=car_orders.id").Where("car_orders.id=?", id).Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": order,
	})
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var order []models.CarOrderList
	redis_key := "list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("car_orders").Select(
			"cars.id AS OrderId",
			"cars.car_model AS CarName",
			"cars.car_name AS CarPrice",
			"cars.car_price AS CarModel",
			"car_orders.order_code AS OrderCode",
			"car_orders.order_num AS OrderNum",
			"car_orders.order_price AS OrderPrice",
		).Joins("LEFT JOIN cars ON cars.id=car_orders.id").
			Offset(offset).Limit(size).Debug().Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	var total int64
	models.DB.Model(&models.CarOrder{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  order,
		"total": total,
	})
}
func OrderAdd(c *gin.Context) {
	order_code := c.PostForm("order_code")
	order_price := c.PostForm("order_price")
	order_num := c.PostForm("order_num")
	data := models.CarOrder{
		Model:      gorm.Model{},
		OrderCode:  order_code,
		OrderNum:   order_price,
		OrderPrice: order_num,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func CarAdd(c *gin.Context) {
	car_name := c.PostForm("car_name")
	car_price := c.PostForm("car_price")
	car_model := c.PostForm("car_model")
	data := models.Car{
		Model:    gorm.Model{},
		CarName:  car_name,
		CarPrice: car_price,
		CarModel: car_model,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
